package com.benmei.weike.util;

import net.rubyeye.xmemcached.MemcachedClient;
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import java.util.Map;

public class MemcachedUtils {
	private static final Logger logger = Logger.getLogger(MemcachedUtils.class);
	private static MemcachedClient memcachedClient;

	static {
		if (memcachedClient == null) {
			ApplicationContext ctx = new FileSystemXmlApplicationContext(
					new String[]{"classpath:/spring/applicationContext.xml"});


			memcachedClient = (MemcachedClient) ctx.getBean("memcachedClient");

		}

	}

	private MemcachedUtils() {
	}


	/**
	 * 仅当缓存中不存在键时，add 命令才会向缓存中添加一个键值对。
	 *
	 * @param key   键
	 * @param value 值
	 * @return
	 */
	public static void add(String key, Object value) {
		add(key, value, null);
	}

	/**
	 * 仅当缓存中不存在键时，add 命令才会向缓存中添加一个键值对。
	 *
	 * @param key    键
	 * @param value  值
	 * @param expire 过期时间 单位：秒，超过30天使用绝对时间，默认30天
	 * @return
	 */
	public static void add(String key, Object value, Integer expire) {
		try {
			if (expire == null) {
				expire = 60 * 60 * 24 * 30;
			}
			memcachedClient.add(key, expire, value);
		} catch (Exception e) {
			// 记录Memcached日志
			logger.error("Memcached add方法报错，key值：" + key, e);
		}
	}


	/**
	 * 仅当键已经存在时，replace 命令才会替换缓存中的键。
	 *
	 * @param key    键
	 * @param value  值
	 * @param expire 过期时间 单位：秒，超过30天使用绝对时间，默认30天
	 * @return
	 */
	public static void replace(String key, Object value, Integer expire) {
		try {
			if (expire == null) {
				expire = 60 * 60 * 24 * 30;
			}
			memcachedClient.replace(key, expire, value);
		} catch (Exception e) {
			logger.error("Memcached replace方法报错，key值：" + key, e);
		}
	}


	/**
	 * get 命令用于检索与之前添加的键值对相关的值。
	 *
	 * @param key 键
	 * @return
	 */
	public static Object get(String key) {
		Object obj = null;
        if (key == null) {
            return null;
        }
        if ("[object Null]".equalsIgnoreCase(key)) {
            logger.error("无效Key:" + key);
            return null;
        }
        try {
			obj = memcachedClient.get(key);
		} catch (Exception e) {
			logger.error("Memcached get方法报错，key值：" + key, e);
		}
		return obj;
	}

	/**
	 * 删除 memcached 中的任何现有值。
	 *
	 * @param key 键
	 * @return
	 */
    public static void delete(String key) throws Exception {
        try {
			memcachedClient.delete(key);
		} catch (Exception e) {
			logger.error("Memcached delete方法报错，key值：" + key, e);
            throw e;
        }
	}

	public static void main(String[] args) {
		String ip = "218.108.146.190";
		Map<String, Integer> map = (Map<String, Integer>) MemcachedUtils.get(ip);
		int size = map.get("size") + 1;
		logger.info("The ip " + ip + " request number of times:" + size);
	}

}